package String;


public class StringExer {
    public static void main(String[] args) {
        String s1 = "abcdefg";
        String s2 = reverse3(s1,2,5);
        System.out.println(s2);
    }

    /*
    * 将一个字符串指定部分进行翻转,例如"abcdefg"翻转为"abfedcg";
    * */

    //方式一:转换为char[]
    static public String reverse1(String str,int startindex,int endindex){
        if (str == null) return null;

        char[] arr = str.toCharArray();
        for (int x = startindex,y = endindex;x<y;x++,y--){
            char temp = arr[x];
            arr[x] = arr[y];
            arr[y] = temp;
        }
        return new String(arr);
    }

    //方式二:使用string的拼接方法
    static public String reverse2(String str,int startindex,int endindex){
        if (str == null) return null;

        //第一部分
        String reverseStr = str.substring(0,startindex);

        //第二部分
        for (int i = endindex; i >= startindex; i--) {
            reverseStr += str.charAt(i);
        }

        //第三部分
        reverseStr = reverseStr + str.substring(endindex, str.length());
       return reverseStr;
    }

    //方式三:使用stringBuffer或StringBuilder
    static public String reverse3(String str,int startindex,int endindex){
        if (str == null) return null;

        StringBuilder builder = new StringBuilder(str.length());

        //第一部分
        builder.append(str.substring(0,startindex));
        //第二部分
        for (int i = endindex; i >= startindex; i--) {
            builder.append(str.charAt(i));
        }
        //第三部分
        builder.append(str.substring(endindex + 1));

       return builder.toString();
    }
}
